﻿Imports System
Imports System.IO
Imports System.Security.Cryptography

Public Class Decryptor
    Private transformer As DecryptTransformer

    Private initVec As Byte()


    Public WriteOnly Property IV() As Byte()

        Set(ByVal value As Byte())
            initVec = value
        End Set
    End Property

    Public Sub New(ByVal algId As EncryptionAlgorithm)
        transformer = New DecryptTransformer(algId)
    End Sub

    Public Function Decrypt(ByVal bytesData As Byte(), ByVal bytesKey As Byte()) As Byte()
        Dim memoryStream As New MemoryStream()
        transformer.IV = initVec
        Dim iCryptoTransform As ICryptoTransform = transformer.GetCryptoServiceProvider(bytesKey)
        Dim cryptoStream As New CryptoStream(memoryStream, iCryptoTransform, CryptoStreamMode.Write)
        Try
            cryptoStream.Write(bytesData, 0, CInt(bytesData.Length))
            cryptoStream.FlushFinalBlock()
            cryptoStream.Close()
            Dim bs As Byte() = memoryStream.ToArray()
            Return bs
        Catch e As Exception

            Throw New Exception([String].Concat("Error while writing encrypted data to the stream: ", e.Message))
        End Try
    End Function

End Class
